//
//  WMEncryptTool.swift
//  SwiftProject
//
//  Created by qindong on 2021/10/22.
//  Copyright © 2021 qindong. All rights reserved.
//

import UIKit
import CryptoSwift
import CommonCrypto

class WMEncryptTool: NSObject {
    static let manager : WMEncryptTool = WMEncryptTool()

    let key = "jScGU3fj8m/tDCyvsbEhwI99M1FcwvQq"
    let iv = "w2wjCNctEG09danP"

    private override init() {

    }

    func decrypt(_ str : String = "0wApId4RX5aZbS3dJPOqy+N3nJhVJHQgEneqtAA3xcgs1yjTg66czrL3V76rf1v/xVjPHBGX9mi43+LjOhoIGA==") {
        let str = str.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: ".", with: "/").replacingOccurrences(of: "!", with: "=")
        do {
            let ase = try AES(key: key, iv: iv)
            if let data = Data(base64Encoded: str) {
                let result = try ase.decrypt([UInt8](data))
                _ = String(data: Data(result), encoding: .utf8)
            }
        } catch {
            print(error)
        }
    }
    
    func aesEncrypt(_ str : String) -> String {
        do {
            let ase = try AES(key: "ree1b7d9ca0b7d10".bytes, blockMode: ECB(), padding: .pkcs7)
            let result = try ase.encrypt(str.bytes)
            return result.toBase64()
        } catch {
            print(error)
        }
        return ""
    }
    
    func aesDecode(_ str : String) -> String {
        do {
            let ase = try AES(key: "ree1b7d9ca0b7d10".bytes, blockMode: ECB(), padding: .pkcs7)
            guard let data = Data(base64Encoded: str) else {
                return ""
            }
            let result = try ase.decrypt([UInt8](data))
            return String(data: Data(result), encoding: .utf8)!
        } catch {
            print(error)
        }
        return ""
    }

    func encrypt(_ str : String = "{\"result_key\":\"1234567890qwertyuiopasdfghjklzxcvbnm\",\"mmm\":11}") -> String {
        do {
            let ase = try AES(key: key, iv: iv)
            if let data = str.data(using: .utf8) {
                let result = try ase.encrypt([UInt8](data))
                let string = result.toBase64()
                let resultString = string.replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: ".").replacingOccurrences(of: "=", with: "!")
                return resultString
            }
        } catch {
            print(error)
        }
        return ""
    }
    
    func des_encrypt_c(timestamp : String) -> String {
        let productKey = "5357744f54584e6f62456f3d"
        let start = timestamp.substring(to: 6)
        let end = timestamp.substring(from: 6)
        let lastChar = timestamp.substring(from: timestamp.count - 1)
        
        let text = Int(lastChar)! % 2 == 0 ? start + productKey + end : end + productKey + start
        return desEncrypt(textString: text, key: "C2uk3HqAg3U=", iv: "g6J0VavO+gc=")!
    }
    
    func desEncrypt(textString : String, key : String, iv : String, options : Int = kCCOptionPKCS7Padding) -> String? {
        if let keyData = Data(base64Encoded: key.data(using: .utf8)!),
            let data = textString.data(using: .utf8),
            let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeDES) {
            let keyLength              = size_t(kCCKeySizeDES)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmDES)
            let options:   CCOptions   = UInt32(options)
            var numBytesEncrypted :size_t = 0
            let cryptStatus = CCCrypt(operation,
                                      algoritm,
                                      options,
                                      keyData.bytes,
                                      keyLength,
                                      Data(base64Encoded: iv.data(using: .utf8)!)!.bytes,
                                      (data as NSData).bytes,
                                      data.count,
                                      cryptData.mutableBytes,
                                      cryptData.length,
                                      &numBytesEncrypted)
            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
                return base64cryptString
            }
            else {
                return nil
            }
        }
        return nil
    }

    ////DES加密
    //function des_encrypt(message) {
    //    var key = CryptoJS.enc.Base64.parse("C2uk3HqAg3U=");
    //    var iv = CryptoJS.enc.Base64.parse("g6J0VavO+gc=");
    //    var encode_str = CryptoJS.TripleDES.encrypt(message, key, {
    //    iv: iv,
    //    mode: CryptoJS.mode.CBC,
    //    padding: CryptoJS.pad.Pkcs7
    //    });
    //    return encode_str.toString();
    //}
    
    //function des_encrypt_c(fn) {
    //    var timestamp = String(new Date().getTime());
    //    var desKey = "C2uk3HqAg3U=";
    //    var productKey = "5357744f54584e6f62456f3d";
    //    var start = timestamp.substring(0, 6);
    //    var end = timestamp.substring(6);
    //    var lastChar = timestamp.substring(timestamp.length-1);
    //
    //    var text;
    //    if (lastChar % 2 == 0) {
    //        text = start + productKey + end;
    //    } else {
    //        text = end + productKey + start;
    //    }
    //    var ciphertext = des_encrypt(text);
    //    var desObj = {
    //        timestamp : timestamp,
    //        ciphertext : des_encrypt(text)
    //    }
    //    fn(desObj)
    //}
    //
}
